package com.demo.apparel.service.web.Impl;

import com.demo.apparel.service.web.WechatApiService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class WechatApiServiceImpl implements WechatApiService {


    private static final String APPID = "wxea4ec594cf3fbb0e";
    private static final String SECRET = "debed3724d0463b85de94e695161b876";

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    public String getOpenidByCode(String code) {
        try {
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token"
                    + "?appid=" + APPID
                    + "&secret=" + SECRET
                    + "&code=" + code
                    + "&grant_type=authorization_code";

            String response = restTemplate.getForObject(url, String.class);
            JsonNode node = mapper.readTree(response);
            return node.path("openid").asText(null);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
